JavaScript Object Methods
Object methods are actions that can be performed on objects.
An object method is a property defoned by a Function.
Property | Value |
---|---|
firstName | John |
lastName | Doe |
age | 50 |
eyeColor | blue |
fullName | function() {return this.firstName + " " + this.lastName;} |
Note:
Methods are functions stored as properties.
Example
const person = {
firstName: "John",
lastName: "Doe",
id: 5566,
fullName: function() {
return this.firstName + " " +
this.lastName;
}
};
Try it Yourself »
Note:
In the example above, this refers to the person object.
this is not a variable. It is a keyword. You cannot change the value of it.
See Also:
Accessing Object Methods
You access an object method with the following syntax:
objectName.methodName()
You will typically describe fullName() as a method of the person object, and fullName as a property.
The fullName property will execute (as a function) when it is invoked with ().
This example accesses the fullName() method of a person object:
If you access the fullName property, without (), it will return the function definition:
Adding a Method to an Object
Adding a new method to an object is easy:
Example
person.name = function () {
return this.firstName + " " + this.lastName;
};
Try it Yourself »
Using Built-In JavaScript Methods
This example uses the toUpperCase()
method of the String object, to convert a text
to uppercase:
let message = "Hello world!";
let x = message.toUpperCase();
The value of x, after execution of the code above will be:
HELLO WORLD!
Example
person.name = function () {
return (this.firstName + " " + this.lastName).toUpperCase();
};
Try it Yourself »